name: CI - Build Application and run tests

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  maven:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15.1-alpine
        env:
          POSTGRES_USER: ${{ secrets.POSTGRES_USERNAME }}
          POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
          POSTGRES_DB: ${{ secrets.POSTGRES_DATABASE }}
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

      redis:
        image: redis:7.2-alpine
        env:
          REDIS_PASSWORD: ${{ secrets.REDIS_PASSWORD }}
        ports:
          - 6379:6379
        options: >-
          --health-cmd "redis-cli ping | grep PONG"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'
          cache: 'maven'

      - name: Create .env file
        run: |
          touch .env
          echo POSTGRES_HOST=${{ secrets.POSTGRES_HOST }} >> .env
          echo POSTGRES_DATABASE=${{ secrets.POSTGRES_DATABASE }} >> .env
          echo POSTGRES_SCHEMA=${{ secrets.POSTGRES_SCHEMA }} >> .env
          echo POSTGRES_USERNAME=${{ secrets.POSTGRES_USERNAME }} >> .env
          echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env
          echo REDIS_HOST=${{ secrets.REDIS_HOST }} >> .env
          echo REDIS_PASSWORD=${{ secrets.REDIS_PASSWORD }} >> .env
          echo JWT_SECRET=${{ secrets.JWT_SECRET }} >> .env
          echo MAIL_HOST=${{ secrets.MAIL_HOST }} >> .env
          echo MAIL_PORT=${{ secrets.MAIL_PORT }} >> .env
          echo MAIL_USERNAME=${{ secrets.MAIL_USERNAME }} >> .env
          echo MAIL_PASSWORD=${{ secrets.MAIL_PASSWORD }} >> .env
          cat .env

      - name: Build and run tests with Maven
        run: mvn -ntp -B verify
